﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Password_Manager
{
    public class AESEncryption
    {
        private const int KeySize = 32; // 256位密钥
        private const int IvSize = 16;  // AES IV固定16字节

        // 生成安全随机密钥
        public string GenerateKey()
        {
            using (var rng = RandomNumberGenerator.Create())
            {
                byte[] key = new byte[KeySize];
                rng.GetBytes(key);
                return Convert.ToBase64String(key);
            }
        }

        // 加密
        public byte[] Encrypt(string key, byte[] data)
        {
            Aes aes = Aes.Create();
            try
            {
                aes.Key = Convert.FromBase64String(key);
                aes.GenerateIV();

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(aes.IV, 0, IvSize); // 写入IV

                    using (CryptoStream cs = new CryptoStream(
                        ms,
                        aes.CreateEncryptor(),
                        CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                    }

                    return ms.ToArray();
                }
            }
            finally
            {
                aes.Dispose();
            }
        }

        // 解密
        public byte[] Decrypt(string key, byte[] encryptedData)
        {
            Aes aes = Aes.Create();
            try
            {
                aes.Key = Convert.FromBase64String(key);

                byte[] iv = new byte[IvSize];
                Array.Copy(encryptedData, 0, iv, 0, IvSize);
                aes.IV = iv;

                using (MemoryStream ms = new MemoryStream(
                    encryptedData,
                    IvSize,
                    encryptedData.Length - IvSize))
                {
                    using (CryptoStream cs = new CryptoStream(
                        ms,
                        aes.CreateDecryptor(),
                        CryptoStreamMode.Read))
                    {
                        using (MemoryStream resultMs = new MemoryStream())
                        {
                            cs.CopyTo(resultMs);
                            return resultMs.ToArray();
                        }
                    }
                }
            }
            finally
            {
                aes.Dispose();
            }
        }
    }
}